package com.usiful.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.usiful.model.FollowSale;
import com.usiful.model.Product;
import com.usiful.schema.UsifulConfigSchema;

/**
 * 
 * @author [周织能]
 * @description usiful 的html工具类
 * @date 2016年7月24日
 * @email 742408364@qq.com
 */
public class UsifulHtmlHelper {

	private  Document homeDoc;
	private static UsifulHtmlHelper instance;
	
	private UsifulHtmlHelper() {
		
	}
	
	public static UsifulHtmlHelper getInstance() {
		if(instance == null) {
			instance = new UsifulHtmlHelper();
		}
		return instance;
	}
	
	/**
	 * 根据页码生成指定页的url
	 * 
	 * @param pageIndex
	 *            页码
	 * @return
	 */
	private String getProductHomeUrlByPageIndex(int pageIndex) {
		String url = UsifulConfigSchema.UsifulProductHomeUrl;
		if (pageIndex <= 1) {
			url = UsifulConfigSchema.UsifulProductHomeUrl + "#_his_";
		} else {
			url = String.format(UsifulConfigSchema.UsifulProductHomeUrl
					+ "?TechnicalForm.SiteMapNodeId=56396&TechnicalForm.DepartmentId=&TechnicalForm.ProductId=&hdnPageType=StoreSeller&TechnicalForm.SellerId=26305&TechnicalForm.PageType=MARKETPLACE_SELLERSHOP&NavigationForm.CurrentSelectedNavigationPath=0&FacetForm.SellerId=26305&SortForm.SelectedSort=BESTSALES&ProductListTechnicalForm.Keyword=&PaginationForm.CurrentPage=%d&PaginationForm.TotalPage=26&page=%d&"
					+ "&_his_", pageIndex,pageIndex);
		}
		return url;
	}
	/**
	 * 加载usiful主页数据
	 * @param isUseCache 如果网络状态不好或者关注流量状态就设置为 true  关注数据的实时性则使用false
	 * @return
	 */
	private Document loadDocumentFromHomeUrl(boolean isUseCache){
		if(homeDoc != null && isUseCache) {
			return homeDoc;
		}
		try {
			homeDoc = Jsoup.connect(UsifulConfigSchema.UsifulProductHomeUrl).timeout(10000).get();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return homeDoc;
	}
	
	/**
	 * 获取usiful店铺主页的产品基本信息列表
	 * @return
	 */
	public List<Product> getUsifulHomeProduct() {
		List<Product> products = new ArrayList<Product>();
		homeDoc = loadDocumentFromHomeUrl(true);
		return products;
	}
	
	public List<Product> parseUsifulProductInfo() {
		int pageCount = getTotalPageCount();
		List<Product> products = new ArrayList<Product>();
		pageCount = 1;
		for (int i = 1; i <= pageCount; i++) {
			List<Product> prods = UsifulHtmlHelper.getInstance().parseUsifulProductInfoByPageIndex(i);
			if (prods != null) {
				products.addAll(prods);
			}
		}
		return products;
	}
	
	public List<Product> parseUsifulProductInfoByPageIndex(int pageIndex) {
		List<Product> products = new ArrayList<Product>();
		Document homeDoc = null;
		try {
			homeDoc = Jsoup.connect(getProductHomeUrlByPageIndex(pageIndex)).get();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(homeDoc != null) {
			Element ulElement = homeDoc.select("ul#lpBloc").get(0);
			Elements liElements = ulElement.children();
			Product product = null;
			for(Element liElement : liElements) {
				product = parse2Product(liElement);
				products.add(product);
			}
			return products;
		}
		return null;
	}

	/**
	 * 获得产品总页数
	 * @param homeDoc
	 * @return
	 */
	public int getTotalPageCount() {
		Document homeDoc = null;
		try {
			homeDoc = Jsoup.connect(getProductHomeUrlByPageIndex(1)).timeout(10000).get();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Element ulPg = homeDoc.select("div.pg").get(0).child(1);
		String value = ulPg.attr("value");
		return Integer.parseInt(value);
	}
	
	/**
	 * 获得产品当前页面
	 * @param homeDoc
	 * @return
	 */
	public int getCurrentPageIndex(Document homeDoc) {
		Element ulPg = homeDoc.select("div.pg").get(0).child(0);
		String value = ulPg.attr("value");
		return Integer.parseInt(value);
	}
	
	
	private Product parse2Product(Element element) {
		Product product = null;
		if(element != null) {
			product = new Product();
			//产品主页链接
			Element homeUrlElement = element.select("a.jsQs").get(0);
			
			//产品描述
			Element descElement = element.select("p.prdtBDesc").get(0);
			//产品售价
			Element priceElement = element.select("span.price").get(0);
			//产品图片
			Element imgElement = element.select("img.prdtBImg").get(0);
			String price = priceElement.text().replace(UsifulConfigSchema.MoneyUnitTag, ".");
			product.setHomeUrl(homeUrlElement.attr("href") + homeUrlElement.attr("data-qs"));
			product.setName(element.select("div.prdtBTit").text());
			product.setDescription(descElement.text());
			product.setImageUrl(imgElement.attr("src"));
			product.setSalePrice(Float.parseFloat(price));
			Set<FollowSale> followSales = extractProductFollowData(product);
			if(followSales != null && followSales.size() > 0) {
				System.out.println(product.getName());
			}
			product.setFollowSales(followSales);
			System.out.println(price);
		}
		return product;
	}
	
	/**
	 * 抓取产品详情页的跟卖数据
	 * @param productPageUrl
	 */
	private Set<FollowSale> extractProductFollowData(Product product) {
		Document productHomeDoc = null;
		try {
			productHomeDoc = Jsoup.connect(product.getHomeUrl()).timeout(10000).get();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(productHomeDoc != null) {
			Elements fpElements = productHomeDoc.select("p.fpOtherOffer");
			if(fpElements != null && fpElements.size() > 0) {
				Element fpElement = fpElements.get(0);
				Element fpA = fpElement.child(0);
				String productFollowUrl = UsifulConfigSchema.BaseUrl + fpA.attr("href");
				Set<FollowSale> followSales = extraFollowDatasFromFollowPage(productFollowUrl);
				System.out.println(product.getName() + "===follow link=>" + productFollowUrl);
				System.out.println(product.getName() + "===follow size=>" + followSales.size());
				return followSales;
				
			}
		}
		return null;
	}
	
	public Set<FollowSale> extraFollowDatasFromFollowPage(String followProductListUrl) {
		Set<FollowSale> followSales = new HashSet<FollowSale>();
		int pageCount = 0;
		Document followSaleDoc = null;
		try {
			followSaleDoc = Jsoup.connect(followProductListUrl).timeout(10000).get();
			String pageC = followSaleDoc.select("input[name=Pagination.TotalPageCount]").get(0).val();
			pageCount = Integer.parseInt(pageC);
			if(pageCount > 0) {
				for(int i = 1; i <= pageCount; i++) {
					followSaleDoc = Jsoup.connect(followProductListUrl)
							.data("Pagination.CurrentPage",String.valueOf(i))
							.data("Pagination.TotalPageCount",String.valueOf(pageCount))
							.data("FiltersAndSorts.ChkFilterToNew",String.valueOf(true))
							.data("FiltersAndSorts.ChkSortByPriceAndShipping",String.valueOf(true))
							.timeout(10000).post();
					if(followSaleDoc != null) {
						Elements fpElements = followSaleDoc.select(".fpBlk.fpTab");
						String name = followSaleDoc.select("div.fpmTDesc").get(0).child(2).text();
						if(fpElements != null && fpElements.size() > 0) {
							for(Element element : fpElements) {
								FollowSale followSale = new FollowSale();
								followSale.setName(name);
								followSale.setShop(element.select("a.slrName").get(0).text());
								followSale.setUrl(UsifulConfigSchema.BaseUrl + "/" + element.select("a.slrName").get(0).attr("href"));
								followSale.setShipPrice(Float.parseFloat(element.select("span.price").get(0).text().replace("Gratuit","0").replace(",",".").replace("€", "")));
								followSale.setSalePrice(Float.parseFloat(element.select("p.price").get(0).text().replace("€", ".")));
								followSale.setPrice(followSale.getShipPrice() + followSale.getSalePrice());
								String productLink = element.select("input#ProductFormData_ProductPostedForm_ProductReturnAddLink").get(0).attr("value");
								followSale.setProductLink(productLink);
								int idxStart = productLink.lastIndexOf("/");
								int idxEnd = productLink.lastIndexOf(".html");
								String magic = productLink.substring(idxStart + 1, idxEnd);
								followSale.setMagic(magic);
								String shipTime = element.select("div .fpSlrCom").get(0).child(0).child(0).child(3).child(1).select("span").get(0).text();
								followSale.setShipTime(shipTime);
								followSales.add(followSale);
							}
						}
					}
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return followSales;
	}
}
